package com.limedia.explorer.centralcontrol;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.RectF;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.PopupWindowCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.limedia.explorer.constant.Constant;
import com.limedia.explorer.entity.ClientView;
import com.limedia.explorer.enums.Enums.ClientNo;
import com.thunder.rebot.rebotclient.R;
import com.thunder.rebot.rebotclient.activity.BaseActivity;
import com.thunder.rebot.rebotclient.activity.TaskActivity;
import com.thunder.rebot.rebotclient.adapter.PersonAdapter;
import com.thunder.rebot.rebotclient.application.RobotApplication;
import com.thunder.rebot.rebotclient.constant.Constants;
import com.thunder.rebot.rebotclient.control.MySurfaceView;
import com.thunder.rebot.rebotclient.control.OnRockerListener;
import com.thunder.rebot.rebotclient.entity.ContentMessageBean;
import com.thunder.rebot.rebotclient.entity.Direction;
import com.thunder.rebot.rebotclient.entity.MapCenterEntity;
import com.thunder.rebot.rebotclient.entity.MessageBean;
import com.thunder.rebot.rebotclient.entity.Network;
import com.thunder.rebot.rebotclient.entity.PersonEntity;
import com.thunder.rebot.rebotclient.entity.QuerySQLEntity;
import com.thunder.rebot.rebotclient.entity.ResponseMessageBean;
import com.thunder.rebot.rebotclient.entity.ScaleEntity;
import com.thunder.rebot.rebotclient.entity.SocketConectState;
import com.thunder.rebot.rebotclient.entity.SpecialEntity;
import com.thunder.rebot.rebotclient.entity.SwitchEntity;
import com.thunder.rebot.rebotclient.entity.TaskDots;
import com.thunder.rebot.rebotclient.entity.TaskMessageBean;
import com.thunder.rebot.rebotclient.entity.WifiEnty;
import com.thunder.rebot.rebotclient.iml.OnCustomMatrixChangedListener;
import com.thunder.rebot.rebotclient.iml.OnCustomOutsidePhotoTapListener;
import com.thunder.rebot.rebotclient.iml.OnCustomScaleChangedListener;
import com.thunder.rebot.rebotclient.iml.OnCustomSingleFlingListener;
import com.thunder.rebot.rebotclient.iml.OnDragListener;
import com.thunder.rebot.rebotclient.iml.OnMyFling;
import com.thunder.rebot.rebotclient.iml.OnScrollListener;
import com.thunder.rebot.rebotclient.iml.OnTvClickListener;
import com.thunder.rebot.rebotclient.iml.SteerWheelListener;
import com.thunder.rebot.rebotclient.service.ServiceClient;
import com.thunder.rebot.rebotclient.utils.AudioRecordDemo;
import com.thunder.rebot.rebotclient.utils.ClientUtils;
import com.thunder.rebot.rebotclient.utils.CommonUtils;
import com.thunder.rebot.rebotclient.utils.LogUtil;
import com.thunder.rebot.rebotclient.utils.RecorderManager;
import com.thunder.rebot.rebotclient.vam.Algo;
import com.thunder.rebot.rebotclient.vam.entity.FaceFrame;
import com.thunder.rebot.rebotclient.vam.entity.MapperParams;
import com.thunder.rebot.rebotclient.vam.entity.ViewSize;
import com.thunder.rebot.rebotclient.vam.ui.DataDrawable;
import com.thunder.rebot.rebotclient.vam.utils.MapperParamsUtils;
import com.thunder.rebot.rebotclient.view.CircleView;
import com.thunder.rebot.rebotclient.view.CustomListviewPopwindow;
import com.thunder.rebot.rebotclient.view.CustomPopwindow;
import com.thunder.rebot.rebotclient.view.MyPhontoView;
import com.ts.robot.socket.TSRobotSocketNative;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ControlActivity extends BaseActivity {

    @BindView(R.id.fl)
    public FrameLayout fl;

    @BindView(R.id.center_txt)
    public TextView centerTxt;
    @BindView(R.id.left_img)
    public ImageView leftImg;
    @BindView(R.id.right_txt)
    public TextView rightTxt;
    @BindView(R.id.ll_controller)
    public RelativeLayout controllView;
    @BindView(R.id.iv_dataview)
    public ImageView mDataView;
    @BindView(R.id.iv_map)
    public MyPhontoView map;


    @BindView(R.id.iv_location)
    public ImageView ivLocation;

    @BindView(R.id.ivChange)
    public ImageView ivChange;


    @BindView(R.id.iv_select_person)
    public ImageView ivSelectPerson;

    @BindView(R.id.ll2)
    public LinearLayout ll2;//在手动切换的情况下，切换UI
    @BindView(R.id.ivStop)
    public ImageView ivStop;

    @BindView(R.id.ivGo)
    public ImageView ivGo;

    @BindView(R.id.rl1)
    public RelativeLayout rl1;//在手动切换的情况下，切换UI

    @BindView(R.id.tvStartPoint)
    public TextView tvStartPoint;
    @BindView(R.id.tvEndPoint)
    public TextView tvEndPoint;
    @BindView(R.id.steerWheel)
    public CircleView steelWheel;

    private static final String TAG = ControlActivity.class.getSimpleName();
    private static final int MSG_DEVICE_RESOLVED = 1;
    private static final int MSG_DEVICE_REMOVED = 2;
    private static final int MSG_DEVICE_ADDED = 3;
    //	private static final int MSG_TEST_STOP_LOADING = 4;
    private float meterTopix = 0.05f;//0.05
    private int deviceNo = 0;

    private ClientView mClient1 = null;
    ;
    private int mCurClientID = 0;
    private int zl = 0;


    private Handler mHandler = null;
    private LocalBroadcastManager mLoaclBroadcastManager = null;
    private LocalReceiver mLocalReceiver = null;
    private Context mContext = null;

    private List<String> clientUrls = new ArrayList<String>();
    private DataDrawable mDataDrawable;
    private boolean isSendSport = false;
    private MapperParams vamParams;
    private int screenWidth;

    private boolean auto = true;//默认是自动
    private int autoOrManual = 1;//1 auto default , 2 manaul

    private MapCenterEntity mce;
    private boolean isfirst = true;
    private boolean isReverse = true;//默认是在初始值

    private SharedPreferences sharedPreferences;

    /*四个坐标点的    icon的初始值*/
    float initxx;
    float inityy;
    float constInitxx;
    float constInityy;

    float initxx2;
    float inityy2;
    float constInitxx2;
    float constInityy2;

    float initxx3;
    float inityy3;
    float constInitxx3;
    float constInityy3;

    float initxx4;
    float inityy4;
    float constInitxx4;
    float constInityy4;
    private int hlength = 2;//二维数组行数4
    private int vlength = 2;//二维数组的列数
    float[][] initxy = new float[hlength][vlength];
    float[][] constInitxy = new float[hlength][vlength];

int i = 0;//遍历
    /*默认边框的初始值*/
    float initLocationleft = 0;
//    float initLocationleftSpace = 0.8;
    float initLocationtop = 24;
//    float initLocationtopSpace = 24.8;
    float initLocationtight = 720;
    float initLocationbottom = 744;

    private float transelateTop = 0;
    private float transelateBottom = 768;

    private int gesture = 0;


    private int deskWidth = 30;
    private int deskHeight = 40;



    /**
     * select person
     */
    private ArrayList<PersonEntity> list;
    private ListView listview;
    private PersonAdapter personAdapter;
    private CustomListviewPopwindow customListviewPopwindow;//select person
    private CustomPopwindow customPopwindow1;//起点还是终点？

    private int start = 0;//0是默认直， 1 是起点
    private int end = 0;//0是默认直，   2 终点


    private RecorderManager recorderManager;
    private Button btnSpecial;
/*
读取本地存储
 */

    private String getTaskDots(){
        sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
        return sharedPreferences.getString("taskdots",null);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_control);
        ButterKnife.bind(this);
        getTaskDots();
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();
        mce = CommonUtils.getMapCenter1(map);
        addTaskDots();

//        inithandle();

        //服务端开始对每一帧视频流进行硬编码和人脸识别
        if(ServiceClient.client != null){
            new Thread("send") {
                @Override
                public void run() {
                    Network.SomeRequest request = new Network.SomeRequest();
                    request.sendType = 4;
                    LogUtil.d(TAG, "客户端发送的 request.sendType==" + request.sendType);
                    ServiceClient.client.sendTCP(request);
                }
            }.start();
        }
        if(mtsRobotSocketNative != null) {
            mtsRobotSocketNative.addSocketLisetnerInterface(this);
        }
        ServiceClient.setOnPackageRemoveListener(ControlActivity.this);
        vamParams = MapperParamsUtils.getMapperParams(
                new ViewSize(1920, 1080), 0,  //视频的尺寸
                new ViewSize(1080, 1920));  //屏幕的尺寸，每个手机不一样 adb shell wm size
        centerTxt.setText(R.string.title_txt);
        rightTxt.setText(R.string.operate_task);
        this.mContext = this;
        this.mLocalReceiver = new LocalReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_SERVICE_RESOLVED);
        intentFilter.addAction(Constant.ACTION_SERVICE_REMOVED);
        intentFilter.addAction(Constant.ACTION_SERVICE_ADDED);
        this.mLoaclBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
        this.mLoaclBroadcastManager.registerReceiver(this.mLocalReceiver, intentFilter);
//        this.initListener();
        this.initView();
//        this.initView1();//paul fix

        initListener();


        //this.startService(new Intent(getApplicationContext(), DeviceDiscoverService.class));

        audioRecordDemo = new AudioRecordDemo();
        Message msg = handler.obtainMessage();
        msg.arg1 = 1;
        handler.sendMessage(msg);

        audioRecordDemo.getNoiseLevel();
        task = new TimerTask() {
            @Override
            public void run() {
                saveSensor();
            }
        };

        timer = new Timer();
//        timer.schedule(task,100,500);



//        recorderManager = new RecorderManager();

    }
    private AudioRecordDemo audioRecordDemo;
    /**
     * 获取wifi列表
     */
    private WifiManager wifiManager;
    private List<ScanResult> listb=null;
    private List<ScanResult> getWifiList(){
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.startScan();
        listb = wifiManager.getScanResults();
        if(listb != null) {
            WifiInfo wi = wifiManager.getConnectionInfo();
            Log.w(TAG, "listb:" + listb.toString() + "'''" + wi.getBSSID());
        }
        return listb;
    }


    int ii = 0;
    private void saveSensor(){
//        QuerySQLEntity.ResponseQuery responseQuery = null;
//        double noise = -0.1f;
////        if (recorderManager != null) {
////            noise = recorderManager.getNoise();
////        }




//        List<ScanResult> wifilists = getWifiList();
//        HashMap<String, String> hashMap = new HashMap<>();
//        WifiEnty wifiEnty  = null;
//        for (ScanResult sr : wifilists) {
//            if(sr.SSID.equals("jyw-450M;;")){
//                wifiEnty = new WifiEnty();
//                wifiEnty.setFrame("1200");
//                wifiEnty.setIndex(ii + "");
//                wifiEnty.setLevel(sr.level +"");
//                ++ii;
//                if(ii > 65536000)ii = 0;
//            }
//        }

        WifiEnty wifiEnty = new WifiEnty();
        wifiEnty.setFrame("1200");
        wifiEnty.setIndex(ii+"");
        wifiEnty.setLevel(""+audioRecordDemo.getNoise());
        if (mtsRobotSocketNative != null && wifiEnty != null){
            mtsRobotSocketNative.send_data_native(new Gson().toJson(wifiEnty));
        }
        ++ii;
        if(wifiEnty != null ){
            Log.w(TAG,"@@@WP wifi:" + wifiEnty.toString());
//        if()
//        responseQuery.hashMap = hashMap;
//        Log.d(TAG,"sensor robot:" + responseQuery.toString());
//        synchronized (this){
//            if(mPrefs != null){
//                SharedPreferences.Editor edit = mPrefs.edit();
//                edit.putString("sensor",new Gson().toJson(responseQuery));
//                edit.commit();
//            }
//            Log.d(TAG,"read mPrefs:" + getSensor());
        }
    }



    private TimerTask task;
    private Timer timer ;

    private RectF rectF;
    private void initListener() {
        steelWheel.setOnSteerWheelListener(new SteerWheelListener() {
            @Override
            public void direction(final CircleView.Dir dir) {
                Direction direction = new Direction();
                direction.setFrame("1016");
                switch (dir){
                    case LEFT:
                        direction.setDirection("3");
                        break;
                    case UP:
                        direction.setDirection("1");

                        break;
                    case RIGHT:
                        direction.setDirection("4");
                        break;
                    case DOWN:
                        direction.setDirection("2");
                        break;
                    case CENTER:
                        direction.setDirection("0");
                        break;

                }

                if (mtsRobotSocketNative != null && !RobotApplication.TEST){
                    mtsRobotSocketNative.send_data_native(new Gson().toJson(direction));
                }
                Log.w(TAG,"@@WP : dection");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ControlActivity.this, "@@wp:" + dir,Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });


        /*缩放*/
        map.setOnScaleChangeListener(new OnCustomScaleChangedListener() {
            @Override
            public void onScaleChange(float scaleFactor, float focusX, float focusY) {
                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; focusX:" + focusX + "; focusY:" + focusY);
                if(isfirst){
//                    constInitxx = textViews.get(0).getX();
//                    constInityy = textViews.get(0).getY();
//
//                    constInitxx2 = textViews.get(1).getX();
//                    constInityy2 = textViews.get(1).getY();
//
//                    constInitxx3 = textViews.get(2).getX();
//                    constInityy3 = textViews.get(2).getY();
//
//                    constInitxx4 = textViews.get(3).getX();
//                    constInityy4 = textViews.get(3).getY();


                    for(i = 0; i < hlength; i ++){
                            constInitxy[i][0] = textViews.get(i).getX();
                            constInitxy[i][1] = textViews.get(i).getY();
                    }

//                    initxx = ivLocation.getX();
//                    inityy = ivLocation.getY();
                    //initxx = 0;//ivLocation.getX();
                    //inityy = 0;//ivLocation.getY();




//paul fix 11.28
//                    constInitxx = ivLocation.getX();
//                    constInityy = ivLocation.getY();
                    isfirst = false;



//                    Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initxx:" + location[0] + "; inityy:" + location[1]);
                }

            if(rectF.left == 0){//

            }
//                int[] location = new int[2];
//                textViews.get(0).getLocationOnScreen(location);
//                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initxx:" + location[0] + "; inityy:" + location[1]);

//                Layout layout = textViews.get(0).getLayout();
//                layout.getTopPadding();
//                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initxx:" + layout.getTopPadding() + "; inityy:" + inityy);

//                float initx = screenWidth/2 + new Double(1.0 /0.05 * (screenWidth /384)).intValue() - 50;
//                float inity = new Double(mce.getyPix()/2).intValue() - new Double(1.0/0.05 * (mce.getyPix() /384)).intValue() - 40;
//                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initx:" + initx + "; inity:" + inity);

//                Log.w(TAG,"@@wp scale after:" + scaleFactor + "; aX:" + (focusX + Math.abs(initxx - focusX) * scaleFactor) + "; aY:" + (focusY + Math.abs(initxx - focusY)*scaleFactor));
                ArrayList<ScaleEntity> l = new ArrayList<>();
                ScaleEntity scaleEntity;
                for(i = 0; i < dots.size(); i ++){
                    scaleEntity = new ScaleEntity();
                    scaleEntity.setScale(scaleFactor);
                    scaleEntity.setAx(initxy[i][0] * scaleFactor - (focusX - constInitxy[i][0]) * (1 - 1/scaleFactor));
                    scaleEntity.setAy(initxy[i][1] * scaleFactor - (focusY - constInitxy[i][1]) * (1 - 1/scaleFactor));
                    l.add(scaleEntity);
                }

                Message msg = handler.obtainMessage();
                msg.arg1 = 10;
                msg.obj = l;
                handler.sendMessage(msg);








//                ScaleEntity scaleEntity = new ScaleEntity();
//                scaleEntity.setScale(scaleFactor);
//                //scaleEntity.setAx((focusX + Math.abs(initxx - focusX) * scaleFactor));
//                //scaleEntity.setAy((focusY + Math.abs(inityy - focusY)*scaleFactor));
//                //scaleEntity.setAx(initxx * scaleFactor - focusX * (1 - 1/scaleFactor) - initxx);
//                //scaleEntity.setAy(inityy * scaleFactor - focusY * (1 - 1/scaleFactor) - inityy);
//                scaleEntity.setAx(initxx * scaleFactor - (focusX - constInitxx) * (1 - 1/scaleFactor));
//                scaleEntity.setAy(inityy * scaleFactor - (focusY - constInityy) * (1 - 1/scaleFactor));
////                scaleEntity.setAx(initxx-1);
////                scaleEntity.setAy(inityy-1);
//                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initxxe:" + (initxx )+ "; inityye:" + inityy );
//
//                Message msg = handler.obtainMessage();
//                msg.arg1 = 10;
//                msg.obj = scaleEntity;
//                handler.sendMessage(msg);
//
//
//                ScaleEntity scaleEntity2 = new ScaleEntity();
//                scaleEntity2.setScale(scaleFactor);
//                //scaleEntity.setAx((focusX + Math.abs(initxx - focusX) * scaleFactor));
//                //scaleEntity.setAy((focusY + Math.abs(inityy - focusY)*scaleFactor));
//                //scaleEntity.setAx(initxx * scaleFactor - focusX * (1 - 1/scaleFactor) - initxx);
//                //scaleEntity.setAy(inityy * scaleFactor - focusY * (1 - 1/scaleFactor) - inityy);
//                scaleEntity2.setAx(initxx2 * scaleFactor - (focusX - constInitxx2) * (1 - 1/scaleFactor));
//                scaleEntity2.setAy(inityy2 * scaleFactor - (focusY - constInityy2) * (1 - 1/scaleFactor));
////                scaleEntity.setAx(initxx-1);
////                scaleEntity.setAy(inityy-1);
//                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initxxe:" + (initxx )+ "; inityye:" + inityy );
//
//                Message msg2 = handler.obtainMessage();
//                msg2.arg1 = 10;
//                msg2.obj = scaleEntity;
//                handler.sendMessage(msg);
//
//                ScaleEntity scaleEntity = new ScaleEntity();
//                scaleEntity.setScale(scaleFactor);
//                //scaleEntity.setAx((focusX + Math.abs(initxx - focusX) * scaleFactor));
//                //scaleEntity.setAy((focusY + Math.abs(inityy - focusY)*scaleFactor));
//                //scaleEntity.setAx(initxx * scaleFactor - focusX * (1 - 1/scaleFactor) - initxx);
//                //scaleEntity.setAy(inityy * scaleFactor - focusY * (1 - 1/scaleFactor) - inityy);
//                scaleEntity.setAx(initxx * scaleFactor - (focusX - constInitxx) * (1 - 1/scaleFactor));
//                scaleEntity.setAy(inityy * scaleFactor - (focusY - constInityy) * (1 - 1/scaleFactor));
////                scaleEntity.setAx(initxx-1);
////                scaleEntity.setAy(inityy-1);
//                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initxxe:" + (initxx )+ "; inityye:" + inityy );
//
//                Message msg = handler.obtainMessage();
//                msg.arg1 = 10;
//                msg.obj = scaleEntity;
//                handler.sendMessage(msg);
//
//                ScaleEntity scaleEntity = new ScaleEntity();
//                scaleEntity.setScale(scaleFactor);
//                //scaleEntity.setAx((focusX + Math.abs(initxx - focusX) * scaleFactor));
//                //scaleEntity.setAy((focusY + Math.abs(inityy - focusY)*scaleFactor));
//                //scaleEntity.setAx(initxx * scaleFactor - focusX * (1 - 1/scaleFactor) - initxx);
//                //scaleEntity.setAy(inityy * scaleFactor - focusY * (1 - 1/scaleFactor) - inityy);
//                scaleEntity.setAx(initxx * scaleFactor - (focusX - constInitxx) * (1 - 1/scaleFactor));
//                scaleEntity.setAy(inityy * scaleFactor - (focusY - constInityy) * (1 - 1/scaleFactor));
////                scaleEntity.setAx(initxx-1);
////                scaleEntity.setAy(inityy-1);
//                Log.w(TAG,"@@wp scale scaleFactor:" + scaleFactor + "; initxxe:" + (initxx )+ "; inityye:" + inityy );
//
//                Message msg = handler.obtainMessage();
//                msg.arg1 = 10;
//                msg.obj = scaleEntity;
//                handler.sendMessage(msg);

            }
        });

        /**在原图片上面，进行滑动，显示距离*/
        map.setOnSingleFlingListener(new OnCustomSingleFlingListener() {
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                Log.w(TAG,"@@wp onFling velocityX:" + velocityX + "; velocityY:" + velocityY  + "scale:"+map.getScale() +"--" +e1.getX() + "--" + "--"+e1.getRawX() +"--" +e1.getY() + "--" + "--"+e1.getRawY() + "--" +e2.getX() + "--" + "--"+e2.getRawX()+ "--" +e2.getY() + "--" + "--"+e2.getRawY());
                return false;
            }
        });
        /**单击屏幕，选择图片中的点 范围x0-1，同理y*/
//        map.setOnPhotoTapListener(new OnCustomPhotoTapListener() {
//            @Override
//            public void onPhotoTap(ImageView view, float x, float y) {
//                Log.w(TAG,"@@wp onPhotoTap x:" + x + "; y:" + y );
//            }
//        });
        map.setOnOutsidePhotoTapListener(new OnCustomOutsidePhotoTapListener() {
            @Override
            public void onOutsidePhotoTap(ImageView imageView) {

            }
        });
        map.setOnFlingListener(new OnMyFling() {
            @Override
            public void onFling(float startX, float startY, float velocityX, float velocityY) {
                Log.w(TAG, "@@@wp:startX:" + startX + " startY:" + startY + " velocityX:" + velocityX + " velocityY:" + velocityY);
            }
        });

        map.setOnMatrixChangeListener(new OnCustomMatrixChangedListener() {
            @Override
            public void onMatrixChanged(RectF rect) {
                rectF = rect;
                Log.w(TAG, "@@@ left:" + rect.left + "top:" + rect.top +"right:" + rect.right + "bootom:" + rect.bottom + "top:" + transelateTop+"transelateBottom:" + transelateBottom + "--" + isReverse);
                if(initLocationleft == rect.left && initLocationtop == rect.top && initLocationtight == rect.right && initLocationbottom == rect.bottom ){
                    isReverse = true;
                }else{
                    isReverse = false;
                    if (initLocationleft == rect.left ) {//到左边 或者右边  x的值都不变化
                        //到top 或者是 bottom
                        if (transelateTop == rect.top ||transelateBottom == rect.bottom) {//  x 的值都是不变化
                            gesture = 2;
                        }else{
                            gesture = 1;
                        }

                    }else if (transelateTop == rect.top ){  //到上边或者底部   y的值不变化
                        //到left 或者是 bootom
                        if (initLocationleft == rect.left ||initLocationtight == rect.right) {//   y的值都是不变化
                            gesture = 4;
                        }else{
                            gesture = 3;
                        }
                    }else if(initLocationtight == rect.right){
                        //到left 或者是 bootom
                        if (transelateTop == rect.top ||transelateBottom == rect.bottom) {//   y的值都是不变化
                            gesture = 6;
                        }else{
                            gesture = 5;
                        }
                    }else if (transelateBottom == rect.bottom){
                        //到left 或者是 bootom
                        if (initLocationleft == rect.left ||initLocationtight == rect.right) {//   y的值都是不变化
                            gesture = 8;
                        }else{
                            gesture = 7;
                        }
                    }else{
                        gesture = 9;
                    }
                }


            }
        });
        map.setOnScrollListener(new OnScrollListener() {
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float dx, float dy) {
//                Log.w(TAG, "@@wp onScroll: distanceX:" + dx + " distanceY:" + dy + ";;;" + e1.toString() + "ppp:" + e2.toString());
                if (e2.getPointerCount() >1){
                    if(!isReverse){
//                        if(e2.getPointerCount() >1 ){return;}
                        Log.w(TAG,"@@wp onScroll: distanceX:" + dx +"------e12:"+(e1.getX()-e2.getX())+ " ------------distanceY:" + dy + "------" + gesture + e2.getPointerCount());
                        switch (gesture){
                            case 1:

                                ArrayList<ScaleEntity> l1 = new ArrayList<>();
                                for(i = 0; i < hlength; i ++){
                                    ScaleEntity scaleEntity = new ScaleEntity();
                                    scaleEntity.setAx(initxy[i][0] );
                                    initxy[i][0] = initxy[i][0] ;
                                    scaleEntity.setAy(initxy[i][1] - dy);
                                    initxy[i][1] = initxy[i][1] - dy;
                                    l1.add(scaleEntity);
                                }
                                Message msg = handler.obtainMessage();
                                msg.arg1 = 10;
                                msg.obj = l1;
                                handler.sendMessage(msg);

//                            ScaleEntity scaleEntity = new ScaleEntity();
//                            scaleEntity.setAx(initxx );
//                            initxx = initxx ;
//                            scaleEntity.setAy(inityy + dy);
//                            inityy = inityy + dy;
//
//
//                            Message msg = handler.obtainMessage();
//                            msg.arg1 = 10;
//                            msg.obj = scaleEntity;
//                            handler.sendMessage(msg);
                                break;
                            case 2:

                                ArrayList<ScaleEntity> l2 = new ArrayList<>();
                                for(i = 0; i < hlength; i ++){
                                    ScaleEntity scaleEntity = new ScaleEntity();
                                    scaleEntity.setAx(initxy[i][0] );
                                    initxy[i][0] = initxy[i][0] ;
                                    scaleEntity.setAy(initxy[i][1]);
                                    initxy[i][1] = initxy[i][1];
                                    l2.add(scaleEntity);
                                }
                                Message msg2 = handler.obtainMessage();
                                msg2.arg1 = 10;
                                msg2.obj = l2;
                                handler.sendMessage(msg2);



//                            ScaleEntity scaleEntity1 = new ScaleEntity();
//                            scaleEntity1.setAx(initxx );
//                            initxx = initxx ;
//                            scaleEntity1.setAy(inityy);
//                            inityy = inityy ;
//                            Message msg1 = handler.obtainMessage();
//                            msg1.arg1 = 10;
//                            msg1.obj = scaleEntity1;
//                            handler.sendMessage(msg1);
                                break;
                            case 3:
                                ArrayList<ScaleEntity> l3 = new ArrayList<>();
                                for(i = 0; i < hlength; i ++){
                                    ScaleEntity scaleEntity = new ScaleEntity();
                                    scaleEntity.setAx(initxy[i][0] - dx);
                                    initxy[i][0] = initxy[i][0] - dx;
                                    scaleEntity.setAy(initxy[i][1]);
                                    initxy[i][1] = initxy[i][1];
                                    l3.add(scaleEntity);
                                }
                                Message msg3 = handler.obtainMessage();
                                msg3.arg1 = 10;
                                msg3.obj = l3;
                                handler.sendMessage(msg3);


//                            ScaleEntity scaleEntity2 = new ScaleEntity();
//                            scaleEntity2.setAx(initxx + dx);
//                            initxx = initxx + dx;
//                            scaleEntity2.setAy(inityy);
//                            inityy = inityy ;
//                            Message msg2 = handler.obtainMessage();
//                            msg2.arg1 = 10;
//                            msg2.obj = scaleEntity2;
//                            handler.sendMessage(msg2);
                                break;
                            case 4:

                                ArrayList<ScaleEntity> l4 = new ArrayList<>();
                                for(i = 0; i < hlength; i ++){
                                    ScaleEntity scaleEntity = new ScaleEntity();
                                    scaleEntity.setAx(initxy[i][0] );
                                    initxy[i][0] = initxy[i][0] ;
                                    scaleEntity.setAy(initxy[i][1]);
                                    initxy[i][1] = initxy[i][1];
                                    l4.add(scaleEntity);
                                }
                                Message msg4 = handler.obtainMessage();
                                msg4.arg1 = 10;
                                msg4.obj = l4;
                                handler.sendMessage(msg4);



//                            ScaleEntity scaleEntity3 = new ScaleEntity();
//                            scaleEntity3.setAx(initxx );
//                            initxx = initxx ;
//                            scaleEntity3.setAy(inityy);
//                            inityy = inityy ;
//                            Message msg3 = handler.obtainMessage();
//                            msg3.arg1 = 10;
//                            msg3.obj = scaleEntity3;
//                            handler.sendMessage(msg3);
                                break;
                            case 5:
                                ArrayList<ScaleEntity> l5 = new ArrayList<>();
                                for(i = 0; i < hlength; i ++){
                                    ScaleEntity scaleEntity = new ScaleEntity();
                                    scaleEntity.setAx(initxy[i][0] );
                                    initxy[i][0] = initxy[i][0] ;
                                    scaleEntity.setAy(initxy[i][1]-dy);
                                    initxy[i][1] = initxy[i][1] -dy;
                                    l5.add(scaleEntity);
                                }
                                Message msg5 = handler.obtainMessage();
                                msg5.arg1 = 10;
                                msg5.obj = l5;
                                handler.sendMessage(msg5);


//                            ScaleEntity scaleEntity4 = new ScaleEntity();
//                            scaleEntity4.setAx(initxx );
//                            initxx = initxx ;
//                            scaleEntity4.setAy(inityy +dy);
//                            inityy = inityy +dy;
//                            Message msg4 = handler.obtainMessage();
//                            msg4.arg1 = 10;
//                            msg4.obj = scaleEntity4;
//                            handler.sendMessage(msg4);
                                break;
                            case 6:

                                ArrayList<ScaleEntity> l6 = new ArrayList<>();
                                for(i = 0; i < hlength; i ++){
                                    ScaleEntity scaleEntity = new ScaleEntity();
                                    scaleEntity.setAx(initxy[i][0] );
                                    initxy[i][0] = initxy[i][0] ;
                                    scaleEntity.setAy(initxy[i][1]);
                                    initxy[i][1] = initxy[i][1] ;
                                    l6.add(scaleEntity);
                                }
                                Message msg6 = handler.obtainMessage();
                                msg6.arg1 = 10;
                                msg6.obj = l6;
                                handler.sendMessage(msg6);

//                            ScaleEntity scaleEntity5 = new ScaleEntity();
//                            scaleEntity5.setAx(initxx );
//                            initxx = initxx ;
//                            scaleEntity5.setAy(inityy);
//                            inityy = inityy ;
//                            Message msg5 = handler.obtainMessage();
//                            msg5.arg1 = 10;
//                            msg5.obj = scaleEntity5;
//                            handler.sendMessage(msg5);
                                break;
                            case 7:

                                ArrayList<ScaleEntity> l7 = new ArrayList<>();
                                for(i = 0; i < hlength; i ++){
                                    ScaleEntity scaleEntity = new ScaleEntity();
                                    scaleEntity.setAx(initxy[i][0] - dx);
                                    initxy[i][0] = initxy[i][0] - dx;
                                    scaleEntity.setAy(initxy[i][1]);
                                    initxy[i][1] = initxy[i][1] ;
                                    l7.add(scaleEntity);
                                }
                                Message msg7 = handler.obtainMessage();
                                msg7.arg1 = 10;
                                msg7.obj = l7;
                                handler.sendMessage(msg7);


//                            ScaleEntity scaleEntity6 = new ScaleEntity();
//                            scaleEntity6.setAx(initxx + dx);
//                            initxx = initxx + dx;
//                            scaleEntity6.setAy(inityy);
//                            inityy = inityy ;
//                            Message msg6 = handler.obtainMessage();
//                            msg6.arg1 = 10;
//                            msg6.obj = scaleEntity6;
//                            handler.sendMessage(msg6);
                                break;
                            case 8:
                                ArrayList<ScaleEntity> l8 = new ArrayList<>();
                                for(i = 0; i < hlength; i ++){
                                    ScaleEntity scaleEntity = new ScaleEntity();
                                    scaleEntity.setAx(initxy[i][0] );
                                    initxy[i][0] = initxy[i][0] ;
                                    scaleEntity.setAy(initxy[i][1]);
                                    initxy[i][1] = initxy[i][1] ;
                                    l8.add(scaleEntity);
                                }
                                Message msg8 = handler.obtainMessage();
                                msg8.arg1 = 10;
                                msg8.obj = l8;
                                handler.sendMessage(msg8);


//                            ScaleEntity scaleEntity7 = new ScaleEntity();
//                            scaleEntity7.setAx(initxx );
//                            initxx = initxx ;
//                            scaleEntity7.setAy(inityy);
//                            inityy = inityy ;
//                            Message msg7 = handler.obtainMessage();
//                            msg7.arg1 = 10;
//                            msg7.obj = scaleEntity7;
//                            handler.sendMessage(msg7);
                                break;
                            case 9:
                                ArrayList<ScaleEntity> l9 = new ArrayList<>();
                                for(i = 0; i < hlength; i ++){
                                    ScaleEntity scaleEntity = new ScaleEntity();
                                    scaleEntity.setAx(initxy[i][0] - dx);
                                    initxy[i][0] = initxy[i][0] - dx;
                                    scaleEntity.setAy(initxy[i][1]- dy);
                                    initxy[i][1] = initxy[i][1]- dy ;
                                    l9.add(scaleEntity);
                                }
                                Message msg9 = handler.obtainMessage();
                                msg9.arg1 = 10;
                                msg9.obj = l9;
                                handler.sendMessage(msg9);


//                            ScaleEntity scaleEntity8 = new ScaleEntity();
//                            scaleEntity8.setAx(initxx + dx);
//                            initxx = initxx + dx;
//                            scaleEntity8.setAy(inityy + dy);
//                            inityy = inityy +dy;
//                            Message msg8 = handler.obtainMessage();
//                            msg8.arg1 = 10;
//                            msg8.obj = scaleEntity8;
//                            handler.sendMessage(msg8);
                                break;
                        }
                    }
                }

                return true;
            }

        });
        map.setOnDragListener(new OnDragListener() {
            @Override
            public void onDrag(MotionEvent ev,float dx, float dy) {
//                Log.w(TAG,"@@wp onDrag: distanceX:" + dx + " distanceY:" + dy + "------" + gesture + ev.getPointerCount());
                if(!isReverse){
                    if(ev.getPointerCount() >1 ){return;}
                    Log.w(TAG,"@@wp onDrag: distanceX:" + dx + " distanceY:" + dy + "------" + gesture + ev.getPointerCount());
                    switch (gesture){
                        case 1:

                            ArrayList<ScaleEntity> l1 = new ArrayList<>();
                            for(i = 0; i < hlength; i ++){
                                ScaleEntity scaleEntity = new ScaleEntity();
                                scaleEntity.setAx(initxy[i][0] );
                                initxy[i][0] = initxy[i][0] ;
                                scaleEntity.setAy(initxy[i][1] + dy);
                                initxy[i][1] = initxy[i][1] + dy;
                                l1.add(scaleEntity);
                            }
                            Message msg = handler.obtainMessage();
                            msg.arg1 = 10;
                            msg.obj = l1;
                            handler.sendMessage(msg);

//                            ScaleEntity scaleEntity = new ScaleEntity();
//                            scaleEntity.setAx(initxx );
//                            initxx = initxx ;
//                            scaleEntity.setAy(inityy + dy);
//                            inityy = inityy + dy;
//
//
//                            Message msg = handler.obtainMessage();
//                            msg.arg1 = 10;
//                            msg.obj = scaleEntity;
//                            handler.sendMessage(msg);
                            break;
                        case 2:

                            ArrayList<ScaleEntity> l2 = new ArrayList<>();
                            for(i = 0; i < hlength; i ++){
                                ScaleEntity scaleEntity = new ScaleEntity();
                                scaleEntity.setAx(initxy[i][0] );
                                initxy[i][0] = initxy[i][0] ;
                                scaleEntity.setAy(initxy[i][1]);
                                initxy[i][1] = initxy[i][1];
                                l2.add(scaleEntity);
                            }
                            Message msg2 = handler.obtainMessage();
                            msg2.arg1 = 10;
                            msg2.obj = l2;
                            handler.sendMessage(msg2);



//                            ScaleEntity scaleEntity1 = new ScaleEntity();
//                            scaleEntity1.setAx(initxx );
//                            initxx = initxx ;
//                            scaleEntity1.setAy(inityy);
//                            inityy = inityy ;
//                            Message msg1 = handler.obtainMessage();
//                            msg1.arg1 = 10;
//                            msg1.obj = scaleEntity1;
//                            handler.sendMessage(msg1);
                            break;
                        case 3:
                            ArrayList<ScaleEntity> l3 = new ArrayList<>();
                            for(i = 0; i < hlength; i ++){
                                ScaleEntity scaleEntity = new ScaleEntity();
                                scaleEntity.setAx(initxy[i][0] + dx);
                                initxy[i][0] = initxy[i][0] + dx;
                                scaleEntity.setAy(initxy[i][1]);
                                initxy[i][1] = initxy[i][1];
                                l3.add(scaleEntity);
                            }
                            Message msg3 = handler.obtainMessage();
                            msg3.arg1 = 10;
                            msg3.obj = l3;
                            handler.sendMessage(msg3);


//                            ScaleEntity scaleEntity2 = new ScaleEntity();
//                            scaleEntity2.setAx(initxx + dx);
//                            initxx = initxx + dx;
//                            scaleEntity2.setAy(inityy);
//                            inityy = inityy ;
//                            Message msg2 = handler.obtainMessage();
//                            msg2.arg1 = 10;
//                            msg2.obj = scaleEntity2;
//                            handler.sendMessage(msg2);
                            break;
                        case 4:

                            ArrayList<ScaleEntity> l4 = new ArrayList<>();
                            for(i = 0; i < hlength; i ++){
                                ScaleEntity scaleEntity = new ScaleEntity();
                                scaleEntity.setAx(initxy[i][0] );
                                initxy[i][0] = initxy[i][0] ;
                                scaleEntity.setAy(initxy[i][1]);
                                initxy[i][1] = initxy[i][1];
                                l4.add(scaleEntity);
                            }
                            Message msg4 = handler.obtainMessage();
                            msg4.arg1 = 10;
                            msg4.obj = l4;
                            handler.sendMessage(msg4);



//                            ScaleEntity scaleEntity3 = new ScaleEntity();
//                            scaleEntity3.setAx(initxx );
//                            initxx = initxx ;
//                            scaleEntity3.setAy(inityy);
//                            inityy = inityy ;
//                            Message msg3 = handler.obtainMessage();
//                            msg3.arg1 = 10;
//                            msg3.obj = scaleEntity3;
//                            handler.sendMessage(msg3);
                            break;
                        case 5:
                            ArrayList<ScaleEntity> l5 = new ArrayList<>();
                            for(i = 0; i < hlength; i ++){
                                ScaleEntity scaleEntity = new ScaleEntity();
                                scaleEntity.setAx(initxy[i][0] );
                                initxy[i][0] = initxy[i][0] ;
                                scaleEntity.setAy(initxy[i][1]+dy);
                                initxy[i][1] = initxy[i][1] +dy;
                                l5.add(scaleEntity);
                            }
                            Message msg5 = handler.obtainMessage();
                            msg5.arg1 = 10;
                            msg5.obj = l5;
                            handler.sendMessage(msg5);


//                            ScaleEntity scaleEntity4 = new ScaleEntity();
//                            scaleEntity4.setAx(initxx );
//                            initxx = initxx ;
//                            scaleEntity4.setAy(inityy +dy);
//                            inityy = inityy +dy;
//                            Message msg4 = handler.obtainMessage();
//                            msg4.arg1 = 10;
//                            msg4.obj = scaleEntity4;
//                            handler.sendMessage(msg4);
                            break;
                        case 6:

                            ArrayList<ScaleEntity> l6 = new ArrayList<>();
                            for(i = 0; i < hlength; i ++){
                                ScaleEntity scaleEntity = new ScaleEntity();
                                scaleEntity.setAx(initxy[i][0] );
                                initxy[i][0] = initxy[i][0] ;
                                scaleEntity.setAy(initxy[i][1]);
                                initxy[i][1] = initxy[i][1] ;
                                l6.add(scaleEntity);
                            }
                            Message msg6 = handler.obtainMessage();
                            msg6.arg1 = 10;
                            msg6.obj = l6;
                            handler.sendMessage(msg6);

//                            ScaleEntity scaleEntity5 = new ScaleEntity();
//                            scaleEntity5.setAx(initxx );
//                            initxx = initxx ;
//                            scaleEntity5.setAy(inityy);
//                            inityy = inityy ;
//                            Message msg5 = handler.obtainMessage();
//                            msg5.arg1 = 10;
//                            msg5.obj = scaleEntity5;
//                            handler.sendMessage(msg5);
                            break;
                        case 7:

                            ArrayList<ScaleEntity> l7 = new ArrayList<>();
                            for(i = 0; i < hlength; i ++){
                                ScaleEntity scaleEntity = new ScaleEntity();
                                scaleEntity.setAx(initxy[i][0] + dx);
                                initxy[i][0] = initxy[i][0] + dx;
                                scaleEntity.setAy(initxy[i][1]);
                                initxy[i][1] = initxy[i][1] ;
                                l7.add(scaleEntity);
                            }
                            Message msg7 = handler.obtainMessage();
                            msg7.arg1 = 10;
                            msg7.obj = l7;
                            handler.sendMessage(msg7);


//                            ScaleEntity scaleEntity6 = new ScaleEntity();
//                            scaleEntity6.setAx(initxx + dx);
//                            initxx = initxx + dx;
//                            scaleEntity6.setAy(inityy);
//                            inityy = inityy ;
//                            Message msg6 = handler.obtainMessage();
//                            msg6.arg1 = 10;
//                            msg6.obj = scaleEntity6;
//                            handler.sendMessage(msg6);
                            break;
                        case 8:
                            ArrayList<ScaleEntity> l8 = new ArrayList<>();
                            for(i = 0; i < hlength; i ++){
                                ScaleEntity scaleEntity = new ScaleEntity();
                                scaleEntity.setAx(initxy[i][0] );
                                initxy[i][0] = initxy[i][0] ;
                                scaleEntity.setAy(initxy[i][1]);
                                initxy[i][1] = initxy[i][1] ;
                                l8.add(scaleEntity);
                            }
                            Message msg8 = handler.obtainMessage();
                            msg8.arg1 = 10;
                            msg8.obj = l8;
                            handler.sendMessage(msg8);


//                            ScaleEntity scaleEntity7 = new ScaleEntity();
//                            scaleEntity7.setAx(initxx );
//                            initxx = initxx ;
//                            scaleEntity7.setAy(inityy);
//                            inityy = inityy ;
//                            Message msg7 = handler.obtainMessage();
//                            msg7.arg1 = 10;
//                            msg7.obj = scaleEntity7;
//                            handler.sendMessage(msg7);
                            break;
                        case 9:
                            ArrayList<ScaleEntity> l9 = new ArrayList<>();
                            for(i = 0; i < hlength; i ++){
                                ScaleEntity scaleEntity = new ScaleEntity();
                                scaleEntity.setAx(initxy[i][0] + dx);
                                initxy[i][0] = initxy[i][0] + dx;
                                scaleEntity.setAy(initxy[i][1]+ dy);
                                initxy[i][1] = initxy[i][1]+ dy ;
                                l9.add(scaleEntity);
                            }
                            Message msg9 = handler.obtainMessage();
                            msg9.arg1 = 10;
                            msg9.obj = l9;
                            handler.sendMessage(msg9);


//                            ScaleEntity scaleEntity8 = new ScaleEntity();
//                            scaleEntity8.setAx(initxx + dx);
//                            initxx = initxx + dx;
//                            scaleEntity8.setAy(inityy + dy);
//                            inityy = inityy +dy;
//                            Message msg8 = handler.obtainMessage();
//                            msg8.arg1 = 10;
//                            msg8.obj = scaleEntity8;
//                            handler.sendMessage(msg8);
                            break;
                    }
                }

            }
        });


    }



    private void initListView(View view){
        list = new ArrayList<>();
        initPersonPopwindow(view);
        PersonEntity pe1 = new PersonEntity();
        pe1.setName("1");
        pe1.setState(0);
        PersonEntity pe2 = new PersonEntity();
        pe2.setName("2");
        pe2.setState(0);
        PersonEntity pe3 = new PersonEntity();
        pe3.setName("3");
        pe3.setState(0);
        PersonEntity pe4 = new PersonEntity();
        pe4.setName("4");
        pe4.setState(0);

        list.add(pe1);
        list.add(pe2);
        list.add(pe3);
        list.add(pe4);

        personAdapter = new PersonAdapter(this,list,R.layout.listview_item);
        listview.setAdapter(personAdapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                initPopwindow(customListviewPopwindow,view,false,position);
            }
        });
    }
    private PersonEntity startPerson;
    private PersonEntity endperson;
    private ImageView ivStart;
    private ImageView ivEnd;
    /**
     * listview 点击item 弹出的popwin
     * @param popupWindow
     * @param flag
     * @param i
     */
    private void initPopwindow(PopupWindow popupWindow,final View view, boolean flag, final int i){
        customPopwindow1 = new CustomPopwindow(this,R.layout.popwindow_startend_point,R.mipmap.popwindow_bg_right);
        customPopwindow1.setWidth(200);
        customPopwindow1.setHeight(60);
        if(flag){

        }else{
            View contentView = customPopwindow1.getContentView();
            contentView.measure(makeDropDownMeasureSpec(customPopwindow1.getWidth()), makeDropDownMeasureSpec(customPopwindow1.getHeight()));
            int offsetX = -Math.abs(customPopwindow1.getContentView().getMeasuredWidth() ) ;
            int firstVisiblePosition = listview.getFirstVisiblePosition();
            int offsetY = getItemHeight(listview) * (i - firstVisiblePosition)+15;
            PopupWindowCompat.showAsDropDown(customPopwindow1, ivSelectPerson, offsetX, offsetY, Gravity.START);
        }


        customPopwindow1.setTvOnclickListener(new OnTvClickListener() {
            @Override
            public void tvClickListener(View v) {
                switch (v.getId()){
                    case R.id.tvStart:
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ControlActivity.this,"起点",Toast.LENGTH_SHORT).show();
                            }
                        });
                        start = 1;
                        //遍历清除以前的起点
                        for (PersonEntity l : list){
                            if (l.getState() == 1){
                                l.setState(0);
                            }
                        }
                        //重新赋值为起点
                        startPerson = list.get(i);
                        startPerson.setState(1);
                        ListAdapter listAdapter = listview.getAdapter();
                        View v1 = listAdapter.getView(i,view,null);
                        ivStart = v1.findViewById(R.id.ivPersonIcon);
                        TextView tv = v1.findViewById(R.id.tvPersonName);
                        ivStart.setImageDrawable(ControlActivity.this.getResources().getDrawable(R.mipmap.start_person));
                        personAdapter.notifyDataSetChanged();
//                        tvStartPoint.setText(startPerson.getName());
                        customPopwindow1.dismiss();
                        if(start == 1 && end == 2){
                            customListviewPopwindow.dismiss();
                        }
                        break;
                    case R.id.tvEnd:
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(ControlActivity.this,"终点",Toast.LENGTH_SHORT).show();
                            }
                        });
                        for (PersonEntity l : list){
                            if (l.getState() == 2){
                                l.setState(0);
                            }
                        }
                        //重新赋值为终点
                        startPerson = list.get(i);
                        startPerson.setState(2);
                        ListAdapter listAdapter2 = listview.getAdapter();
                        View v2 = listAdapter2.getView(i,view,null);
                         ivEnd= v2.findViewById(R.id.ivPersonIcon);
                        TextView tv2 = v2.findViewById(R.id.tvPersonName);
                        ivEnd.setImageDrawable(ControlActivity.this.getResources().getDrawable(R.mipmap.end_person));
                        Toast.makeText(ControlActivity.this,"555",Toast.LENGTH_SHORT).show();
                        personAdapter.notifyDataSetChanged();
//                        tvEndPoint.setText(startPerson.getName());
                        end = 2;
                        customPopwindow1.dismiss();
                        if(start == 1 && end == 2){
                            customListviewPopwindow.dismiss();
                        }
                        break;
                }
            }
        });
    }

    /**
     * listview
     * @param listview
     * @return
     */
    private int getItemHeight(ListView listview){
        ListAdapter listAdapter = listview.getAdapter();
        if (listAdapter == null) {
            return 0;
        }
        View listItem = listAdapter.getView(0, null, listview);
        listItem.measure(0, 0);
        return listItem.getMeasuredHeight();
    }
    private void initPersonPopwindow(View v){
        if(customListviewPopwindow != null && customListviewPopwindow.isShowing()){customListviewPopwindow.dismiss();}
        customListviewPopwindow = new CustomListviewPopwindow(this,R.layout.listview_person);
        customListviewPopwindow.setWidth(140);
        customListviewPopwindow.setHeight(200);

        listview = customListviewPopwindow.getListview();
//        customListviewPopwindow.setTvOnclickListener(new OnTvClickListener() {
//            @Override
//            public void tvClickListener(View v) {
//                switch (v.getId()){
//                    case R.id.tvStart:
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Toast.makeText(TestActivity.this,"起点",Toast.LENGTH_SHORT).show();
//                            }
//                        });
//                        break;
//                    case R.id.tvEnd:
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                Toast.makeText(TestActivity.this,"终点",Toast.LENGTH_SHORT).show();
//                            }
//                        });
//                        break;
//
//                }
//            }
//        });
    }

    @SuppressWarnings("ResourceType")
    private static int makeDropDownMeasureSpec(int measureSpec) {
        int mode;
        if (measureSpec == ViewGroup.LayoutParams.WRAP_CONTENT) {
            mode = View.MeasureSpec.UNSPECIFIED;
        } else {
            mode = View.MeasureSpec.EXACTLY;
        }
        return View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(measureSpec), mode);
    }
private String endPointName = "";
    private String startPointName = "";
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    Log.i(TAG,"@@@wp:" + zx + "--" + zy + "--");
                    translate1((mce.getxPix() / 2) + Float.valueOf((zx / meterTopix) * mce.getxPix() / origeWidth), -Float.valueOf(mce.getyPix() / 2) + Float.valueOf((zy / meterTopix)) * mce.getxPix() / origeHeight);
                    break;
                case 1://出世位置
                    translate1(Float.valueOf(mce.getxPix() / 2), -Float.valueOf(mce.getyPix() / 2));
                    break;
                case 2://手自动切换同时界面要切换
                    //更新UI
                    if(RobotApplication.TEST){
                        if(autoOrManual == 1)  {//自动
                            //visible
                            steelWheel.setVisibility(View.GONE);
//                            ivSelectPerson.setVisibility(View.VISIBLE);
                            ll2.setVisibility(View.VISIBLE);
                            rl1.setVisibility(View.VISIBLE);
                            ivChange.setImageResource(R.mipmap.auto_change);
                        }else{//手动
                            steelWheel.dir = CircleView.Dir.UNDEFINE;
                            steelWheel.setVisibility(View.VISIBLE);
//                            ivSelectPerson.setVisibility(View.INVISIBLE);
                            ll2.setVisibility(View.INVISIBLE);
                            rl1.setVisibility(View.INVISIBLE);
                            ivChange.setImageResource(R.mipmap.manual_change);
                        }
                    }else {
                        visibleCompant(msg.arg2);
                    }

                    break;
                case  3:

                    break;
                case 10:
//                    ScaleEntity scaleEntity = (ScaleEntity) msg.obj;
//                    translate(scaleEntity.getAx(),scaleEntity.getAy());

                    ArrayList<ScaleEntity> scaleEntitys = (ArrayList<ScaleEntity>) msg.obj;
                    translate20(scaleEntitys);
                    break;
                case 11:
                    TextView tv = (TextView) msg.obj;
                    for (TextView t: ttHashMap.keySet()){
                        if(ttHashMap.get(t).getState() == 1){
                            ttHashMap.get(t).setState(0);
                            t.setBackground(ControlActivity.this.getResources().getDrawable(R.mipmap.gongwei_default));
                        }
                    }
                    ttHashMap.get(tv).setState(1);
                    startPointName = ttHashMap.get(tv).getName();
//                    tvStartPoint.setText(ttHashMap.get(tv).getName());
                    tv.setBackground(ControlActivity.this.getResources().getDrawable(R.mipmap.gongwei_start));
                    Message mm = handler.obtainMessage();
                    mm.arg1 = 13;
                    handler.sendMessage(mm);
                    break;
                case 12 :
                    TextView tv1 = (TextView) msg.obj;
                    for (TextView t: ttHashMap.keySet()){
                        if(ttHashMap.get(t).getState() == 2){
                            ttHashMap.get(t).setState(0);
                            t.setBackground(ControlActivity.this.getResources().getDrawable(R.mipmap.gongwei_default));
                        }
                    }
                    ttHashMap.get(tv1).setState(2);
                    endPointName = ttHashMap.get(tv1).getName();
//                    tvEndPoint.setText(ttHashMap.get(tv1).getName());
                    tv1.setBackground(ControlActivity.this.getResources().getDrawable(R.mipmap.gongwei_end));
                    Message mm1 = handler.obtainMessage();
                    mm1.arg1 = 13;
                    handler.sendMessage(mm1);
                    break;
                case 13:
                    tvStartPoint.setText(startPointName);
                    tvEndPoint.setText(endPointName);
                    break;
                case 14:
                    if(RobotApplication.TEST){
                        if(autoOrManual == 1)  {//自动
                            //visible
                            steelWheel.setVisibility(View.GONE);
                            ivSelectPerson.setVisibility(View.VISIBLE);
                            ll2.setVisibility(View.VISIBLE);
                            rl1.setVisibility(View.VISIBLE);
                            ivChange.setImageResource(R.mipmap.auto_change);
                        }else{//手动
                            steelWheel.dir = CircleView.Dir.UNDEFINE;
                            steelWheel.setVisibility(View.VISIBLE);
                            ivSelectPerson.setVisibility(View.INVISIBLE);
                            ll2.setVisibility(View.INVISIBLE);
                            rl1.setVisibility(View.INVISIBLE);
                            ivChange.setImageResource(R.mipmap.manual_change);
                        }
                    }else {
                        switch((String)msg.obj){
                            case "-1":
                                Toast.makeText(ControlActivity.this,"模式切换失败",Toast.LENGTH_SHORT).show();
                                break;
                            case "0":
                                Toast.makeText(ControlActivity.this,"请再试一次",Toast.LENGTH_SHORT).show();
                                break;
                            case "1":
                                if(autoOrManual == 1)  {//自动
                                    //visible
                                    steelWheel.setVisibility(View.GONE);
                                    ivSelectPerson.setVisibility(View.VISIBLE);
                                    ll2.setVisibility(View.VISIBLE);
                                    rl1.setVisibility(View.VISIBLE);
                                    ivChange.setImageResource(R.mipmap.auto_change);
                                }else{//手动
                                    steelWheel.dir = CircleView.Dir.UNDEFINE;
                                    steelWheel.setVisibility(View.VISIBLE);
                                    ivSelectPerson.setVisibility(View.INVISIBLE);
                                    ll2.setVisibility(View.INVISIBLE);
                                    rl1.setVisibility(View.INVISIBLE);
                                    ivChange.setImageResource(R.mipmap.manual_change);
                                }
//                            Log.d(TAG,"$$ AUTO:" + switchEntity.toString());
                                Toast.makeText(ControlActivity.this,"切换成功",Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }

                    break;
                case 15:
//                    double noise = 0.1f;
//                    if(recorderManager != null){
//                        recorderManager.getNoiseLevel();
//                        noise = recorderManager.getNoise();
//                        Log.w(TAG,"JJJ:" + noise);
//                    }


                    QuerySQLEntity.ResponseQuery response = (QuerySQLEntity.ResponseQuery) msg.obj;
                    tvNoise.setText(response.voice + "----" + response.wificount);
//                    if(response.hashMap != null){
//                        tvTips.setText( response.hashMap.toString());
//                        if(response.hashMap.size() < 1){
//                            Toast.makeText(ControlActivity.this,"@@ hashmap:" + response.hashMap.toString()+"请再试一次",Toast.LENGTH_SHORT).show();
//                        }
//                    }

                    Log.d(TAG,"sensor client:" + response.toString());
                    if(mtsRobotSocketNative != null){
                        mtsRobotSocketNative.send_data_native(new Gson().toJson(response));
                    }
                    break;
                case 16:
                    if(msg.obj instanceof MessageBean){
                        final MessageBean mb = (MessageBean)msg.obj;
                        new Thread("send") {
                            @Override
                            public void run() {
                                //发送给robot,通知扫描人脸成功
                                mtsRobotSocketNative.send_data_native(new Gson().toJson(mb));
                            }
                        }.start();
                        final MessageBean mb1 = new MessageBean();
                        mb1.setID(mb.getID());
                        mb1.setFRAME(TSRobotSocketNative.CONFIRM_OP);
                        alert("\" " + mb.getID() + " \""+"确定装货完成了吗？" , TSRobotSocketNative.CONFIRM_OP,mb1);
                    Log.d(TAG, "@@@@WP :" + mb1 + "-----mb:" + mb);
                    }

                    break;
                case 17:
                    ContentMessageBean o = (ContentMessageBean)msg.obj;
                    alert(((ContentMessageBean) o).getTXT(),"0",null);
                    break;
                case 200:
                    Toast.makeText(getApplicationContext(), msg.obj+"", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private static TSRobotSocketNative mtsRobotSocketNative;

    public static void setRobotSocket(TSRobotSocketNative mtsRobotSocketNative) {
        ControlActivity.mtsRobotSocketNative = mtsRobotSocketNative;
    }
    @Override
    public void conectState(int code,final String description) {
        switch (code) {
            case 1:
                Gson gson = new Gson();
                final SocketConectState socketConectState = gson.fromJson(description, new TypeToken<SocketConectState>() {
                }.getType());

                switch (Integer.valueOf(socketConectState.getCode())) {
                    case 10://连接成功
                        ClientUtils.robotConnectFlag = true;
                        break;
                    case 9://连接断开
                        ClientUtils.robotConnectFlag = false;

                        break;
                    case 8://未连接成功
                        ClientUtils.robotConnectFlag = false;
                        break;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ControlActivity.this, socketConectState.getDescription(), Toast.LENGTH_SHORT).show();
                    }
                });

                break;
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        if(mtsRobotSocketNative != null) {
            mtsRobotSocketNative.addSocketLisetnerInterface(this);
        }
        isShow= true;
    }
boolean isShow = false;
    @Override
    protected void onPause() {
        super.onPause();
        isShow= false;
    }

    @Override
    protected void onStop() {
        super.onStop();
//
    }

    private float x0 = 0.0f;
    private float y0 = 0.0f;

    private float zx;
    private float zy;

    @Override
    public void getLocation(String x, String y, String z, String w) {
        super.getLocation(x, y, z, w);

        zx = Float.valueOf(x);
        zy = Float.valueOf(y);
        Message msgg = handler.obtainMessage();
        msgg.arg1 = 0;
        handler.sendMessage(msgg);
    }

    /**
     * 机器人坐标以及移动的点
     * @param x
     * @param y
     */

    private void translate1(float x, float y) {
        TranslateAnimation translateAnimation = new TranslateAnimation(x0, x, (0 - y0), (0 - y));
//        TranslateAnimation translateAnimation = new TranslateAnimation((0 - y0)/2*(-1), (0 - y)/2*(-1),x0/2, x/2);
        translateAnimation.setDuration(50);
        translateAnimation.setFillAfter(true);
        ivLocation.setAnimation(translateAnimation);
        ivLocation.startAnimation(translateAnimation);

        x0 = x;
        y0 = y;

//        x0 = y;
//        y0 = x;
        translateAnimation = null;
    }
    /**
     * 静态坐标点 的平移
     * @param x
     * @param y
     */




    private void translate(float x, float y) {
        TranslateAnimation translateAnimation = new TranslateAnimation((initxx), (x), (inityy), (y));
        translateAnimation.setDuration(50);
        translateAnimation.setFillAfter(true);

//test
        textViews.get(0).setAnimation(translateAnimation);
        textViews.get(0).startAnimation(translateAnimation);

        //paul fix 11.28
//        ivLocation.setAnimation(translateAnimation);
//        ivLocation.startAnimation(translateAnimation);
        Log.w(TAG,"preLocation: (" + initxx + ", " + inityy + "),  afterLocation: (" + x + ", " + y + ")");

        initxx = x;
        inityy = y;
        translateAnimation = null;
    }
    private void translate20(ArrayList<ScaleEntity> scaleEntitys) {

        for (i = 0; i < dots.size(); i ++){

            ObjectAnimator translationX = ObjectAnimator.ofFloat(textViews.get(i),"translationX",initxy[i][0],(scaleEntitys.get(i)).getAx());
            ObjectAnimator translationY = ObjectAnimator.ofFloat(textViews.get(i),"translationY",initxy[i][1],scaleEntitys.get(i).getAy());

            AnimatorSet animatorSet = new AnimatorSet();  //组合动画
            animatorSet.playTogether(translationX,translationY); //设置动画
            animatorSet.setDuration(300);  //设置动画时间
            animatorSet.start(); //启动
            initxy[i][0] = (scaleEntitys.get(i).getAx());
            initxy[i][1] = scaleEntitys.get(i).getAy();
//            translateAnimation = null;

//            TranslateAnimation translateAnimation = new TranslateAnimation((initxy[i][0]), (scaleEntitys.get(i).getAx()), (initxy[i][1]), scaleEntitys.get(i).getAy());
//            translateAnimation.setDuration(50);
//            translateAnimation.setFillAfter(true);
//
//            textViews.get(i).setAnimation(translateAnimation);
//            textViews.get(i).startAnimation(translateAnimation);
//
//
//            initxy[i][0] = (scaleEntitys.get(i).getAx());
//            initxy[i][1] = scaleEntitys.get(i).getAy();
//            translateAnimation = null;
        }





//test


        //paul fix 11.28
//        ivLocation.setAnimation(translateAnimation);
//        ivLocation.startAnimation(translateAnimation);
//        Log.w(TAG,"preLocation: (" + initxx2 + ", " + inityy2 + "),  afterLocation: (" + x + ", " + y + ")");

    }
    private void initView1() {
        MySurfaceView myView = new MySurfaceView(this);
        myView.setRockerListener(new myFingerEven());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.setMargins(50, 30, 50, 30);
        controllView.addView(myView, lp);
    }

    @Override
    public void onDestroy() {
        Log.i("onDestroy()", "in");

        this.mLoaclBroadcastManager.unregisterReceiver(this.mLocalReceiver);
        this.mClient1.releasePlayer();
        //this.stopService(new Intent(getApplicationContext(), DeviceDiscoverService.class));
        Log.i("onDestroy()", "out");
        //服务端停止视频流的处理
        if(ServiceClient.client != null){
            new Thread("send") {
                @Override
                public void run() {
                    Network.SomeRequest request = new Network.SomeRequest();
                    request.sendType = 5;
                    LogUtil.d(TAG, "客户端发送的 request.sendType==" + request.sendType);
                    ServiceClient.client.sendTCP(request);
                }
            }.start();
        }
        if(audioRecordDemo != null)audioRecordDemo.setGetVoiceRun(false);
        super.onDestroy();
    }

    private CustomPopwindow customPopwindow;
    private void initPopwindow(final TextView testGet, boolean flag) {
        customPopwindow = new CustomPopwindow(this, R.layout.popwindow_startend_point, R.mipmap.popwindow_bg_bottom);
        customPopwindow.setWidth(200);
        customPopwindow.setHeight(60);
        if (flag) {
            View contentView = customPopwindow.getContentView();
            contentView.measure(makeDropDownMeasureSpec(customPopwindow.getWidth()), makeDropDownMeasureSpec(customPopwindow.getHeight()));

            int offsetX = -Math.abs(testGet.getHeight() + customPopwindow.getWidth()/2) ;
            int offsetY = -testGet.getHeight() - customPopwindow.getWidth()/3;
            PopupWindowCompat.showAsDropDown(customPopwindow, testGet, offsetX, offsetY, Gravity.START);
        } else {

        }


        customPopwindow.setTvOnclickListener(new OnTvClickListener() {
            @Override
            public void tvClickListener(View v) {
                switch (v.getId()) {
                    case R.id.tvStart:
                        Message msg = handler.obtainMessage();
                        msg.arg1 = 11;
                        msg.obj = testGet;
                        handler.sendMessage(msg);

                        customPopwindow.dismiss();
                        break;
                    case R.id.tvEnd:
                        Message msg1 = handler.obtainMessage();
                        msg1.arg1 = 12;
                        msg1.obj = testGet;
                        handler.sendMessage(msg1);
                        customPopwindow.dismiss();
                        break;
                }
            }
        });
    }
    private int origeWidth = 1056;
    private int origeHeight = 832;
    private ArrayList<TaskDots> dots;
    private ArrayList<TextView> textViews;
    private HashMap<TextView,TaskDots> ttHashMap = new HashMap<>();
    private void addTaskDots() {
        if(dots == null) {
            dots = new ArrayList<>();
        }
        TaskDots td1 = new TaskDots();
        td1.setId("1");
        td1.setName("1");
        td1.setX(0f);
        td1.setY(-1.0f);

        TaskDots td2 = new TaskDots();
        td2.setId("2");
        td2.setName("2");

        td2.setX(14.372f);
        td2.setY(7.416f);


        TaskDots td3 = new TaskDots();
        td3.setId("3");
        td3.setName("3");
        td3.setX(4);
        td3.setY(3);

        TaskDots td4 = new TaskDots();
        td4.setId("4");
        td4.setName("4");
        td4.setX(1);
        td4.setY(3);
        dots.add(td1);
        dots.add(td2);
//        dots.add(td3);
//        dots.add(td4);
        int i = 0;
        textViews = new ArrayList<>();
        for (final TaskDots td : dots){
            final TextView tvIcon1 = new TextView(this);
            tvIcon1.setClickable(true);
            tvIcon1.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //弹出dialog

                            initPopwindow(tvIcon1, true);
                        }
                    });
            ttHashMap.put(tvIcon1,td);
            tvIcon1.setBackground(this.getResources().getDrawable(R.mipmap.gongwei_default));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(deskWidth, deskHeight);//100,80
            lp.setMargins(screenWidth/2 + new Double(td.getX() /0.05 * (screenWidth /origeWidth)).intValue() - deskWidth /2,
                    new Double(mce.getyPix()/2).intValue() - new Double(td.getY()/0.05 * (mce.getyPix() /origeHeight)).intValue() - deskHeight/2,
                    screenWidth/2 - new Double(td.getX()/0.05 * screenWidth /origeWidth).intValue() + deskWidth/2 ,
                    new Double( mce.getyPix()/2 + td.getY()/0.05 * (mce.getyPix() /origeHeight) + deskHeight/2).intValue());

            textViews.add(tvIcon1);
            fl.addView(tvIcon1, lp);

        }

    }


















//private void  inithandle(){
//    handler = new Handler(Looper.getMainLooper(), new Callback() {
//        @Override
//        public boolean handleMessage(Message msg) {
//            switch(msg.arg1){
//                case 200:
//
//                    break;
//
//            }
//            return false;
//        }
//    });
//}




//    private void initListener() {
//        this. = new Handler(Looper.getMainLooper(), new Callback() {
//
//            @Override
//            public boolean handleMessage(Message msg) {
//                Bundle bundle = null;
//                switch (msg.what) {
//                    case MSG_DEVICE_RESOLVED:
//                        bundle = msg.getData();
//                        onDeviceResolved(bundle.getString("ip"));
//                        break;
//                    case MSG_DEVICE_REMOVED:
//                        break;
//                    case MSG_DEVICE_ADDED:
//                        break;
////				case MSG_TEST_STOP_LOADING:
////					mClient1.stopLoading();
////					mClient3.stopLoading();
////					break;
//                }
//                return true;
//            }
//        });
//    }
private Button btnSensor;
    private TextView tvTips;
    private TextView tvNoise;
    private boolean stop = false;

    private void initView() {
//        final WifiLIstAndVoices.Request request = new WifiLIstAndVoices.Request();
//        request.type = 1000;
        final SpecialEntity se = new SpecialEntity();
        se.setFrame("1201");

        final QuerySQLEntity.RequestQuery query = new QuerySQLEntity.RequestQuery();
        query.type = 12;
        btnSpecial = findViewById(R.id.btnSpecial);
        btnSpecial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mtsRobotSocketNative != null){
                    stop = !stop;
                    se.setStop(stop + "");
                    mtsRobotSocketNative.send_data_native(new Gson().toJson(se));
                }
            }
        });
        tvNoise = findViewById(R.id.tvNoise);
        tvTips = findViewById(R.id.tvTips);
        btnSensor = findViewById(R.id.btn_sensor);
        btnSensor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new Thread("sensor") {
                    @Override
                    public void run() {
//                        super.run();
                        ServiceClient.client.sendTCP(query);
                    }
                }.start();
            }
        });
        //手动和自动切换
        ivChange.setVisibility(View.VISIBLE);
        rightTxt.setVisibility(View.GONE);
        initListView(ivSelectPerson);

        mDataDrawable = new DataDrawable(this, new Algo.FaceMatcher() {
            @Override
            public boolean match(FaceFrame frame1, FaceFrame frame2) {
                return false;
            }
        });
        mDataView.setImageDrawable(mDataDrawable);
        this.mClient1 = new ClientView();
        this.mClient1.setmSurfaceView((SurfaceView) this.findViewById(R.id.preview_first).findViewById(R.id.surfaceView));
        this.mClient1.setBackgroundView(this.findViewById(R.id.preview_first).findViewById(R.id.backgroundView));
        this.mClient1.setLoadingParam(
                (TextView) this.findViewById(R.id.preview_first).findViewById(R.id.loadingText),
                (ImageView) this.findViewById(R.id.preview_first).findViewById(R.id.loadingView),
                AnimationUtils.loadAnimation(this.mContext, R.anim.loading_animation));
        this.mClient1.setClientID("Camera 1");
        this.mClient1.setmClientNo(ClientNo.Client_ONE);
        this.mClient1.startLoading();
        SharedPreferences sharedPreferences = getSharedPreferences("ip", MODE_PRIVATE);
        String firstIpvalue = sharedPreferences.getString("FirstIpAddress", "");
        Log.e(TAG, "Address1" + firstIpvalue);

        this.onDeviceResolved(firstIpvalue);
    }

    protected void onDeviceResolved(String ip) {
        String url = Constant.PREFIX_RTSP_ADDR + ip + Constant.SUFFIX_RTSP_ADDR;
        Log.d(TAG, "onDeviceResolved: url is " + url);
        if (!this.clientUrls.contains(url)) {
            this.clientUrls.add(url);
            Log.d(TAG, "onDeviceResolved: add url--" + url);
            switch (++deviceNo) {
                case 1:
                    Log.d(TAG, "start client: " + deviceNo);
//				mClient1.setRtspUrl("rtsp://192.168.1.117:8899/live");
                    mClient1.setRtspUrl(url);
//				Toast.makeText(this.mContext, "Connect to client 1: " + url, Toast.LENGTH_SHORT).show();
                    if (mClient1.isSurfaceCreated()) {
                        mClient1.startPlayer();
                    } else {
                        mClient1.setDeviceAttached(true);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Message message = Message.obtain();
            Bundle bundle = new Bundle();
            switch (intent.getAction()) {
                case Constant.ACTION_SERVICE_RESOLVED:
                    String ip = intent.getStringExtra("ip");
                    Log.d(TAG, "ACTION_SERVICE_RESOLVED: ip is " + ip);
                    bundle.putString("ip", ip);
                    message.what = MSG_DEVICE_RESOLVED;
                    message.setData(bundle);
                    mHandler.sendMessage(message);
                    break;
                case Constant.ACTION_SERVICE_REMOVED:
                    break;
                case Constant.ACTION_SERVICE_ADDED:
                    break;
                default:
                    break;
            }
        }
    }

    @OnClick({R.id.left_img, R.id.right_txt,R.id.ivChange,R.id.iv_select_person,R.id.ivGo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_img:
                finish();
                //转一圈
//                byte[] value;
//                value = new byte[1];
//                value[0] = (byte) 'B';//摇杆1;
//                mChatService.write(value);
//                try {
//                    Thread.sleep(1950);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                value = new byte[1];
//                value[0] = (byte) 'Z';//摇杆1;
//                mChatService.write(value);
                break;
            case R.id.right_txt://发布任务
//                Intent intentMain = new Intent(this, RegisterActivity.class);
//                startActivity(intentMain);
//                finish();
//                DialogUtils.showAlertDialog(ControlActivity.this);
                Intent intent = new Intent(ControlActivity.this, TaskActivity.class);
                startActivity(intent);
                break;
            case R.id.ivChange://手动和自动的切换
                auto = !auto;
                if(auto){//默认是自动
                    autoOrManual = 1;
//                    ivChange.setImageResource(R.mipmap.auto_change);
                }else{//切换成手动
                    autoOrManual = 0;
//                    ivChange.setImageResource(R.mipmap.manual_change);
                }
                //更新UI
                Message msg = handler.obtainMessage();
                msg.arg1 = 2;
                msg.arg2 = autoOrManual;
                handler.sendMessage(msg);
                break;
            case R.id.iv_select_person://popwindow   select people
                showListviewPopwindow(customListviewPopwindow,ivSelectPerson);
                break;
            case R.id.ivGo:
                if (TextUtils.isEmpty(tvStartPoint.getText().toString().trim()) || TextUtils.isEmpty(tvEndPoint.getText().toString().trim())){

                    Toast.makeText(ControlActivity.this, "起点和终点不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                //下任务
                /*

                 */
                String name = null;
                if(sharedPreferences != null){
                    name = sharedPreferences.getString("username",null);
                }

                if(TextUtils.isEmpty(name)){
                    return;
                }
//                String start = ControlActivity.this.getResources().getStringArray(R.array.locations)[startFrom];
//                String end = ControlActivity.this.getResources().getStringArray(R.array.locations)[endTo];
                //开始发送任务

               alert(name);
                break;
        }
    }
    private void showListviewPopwindow(CustomListviewPopwindow customListviewPopwindow,View v){
        View contentView = customListviewPopwindow.getContentView();
        contentView.measure(makeDropDownMeasureSpec(customListviewPopwindow.getWidth()), makeDropDownMeasureSpec(customListviewPopwindow.getHeight()));
        int offsetX = -customListviewPopwindow.getContentView().getMeasuredWidth();
        int offsetY = -(customListviewPopwindow.getContentView().getMeasuredWidth() +ivSelectPerson.getWidth())/2;
        PopupWindowCompat.showAsDropDown(customListviewPopwindow, v, 0, 0, Gravity.START);
    }

    private void visibleCompant(int autoOrManual) {
        SwitchEntity switchEntity = new SwitchEntity();
        switchEntity.setFRAME("1011");
        switchEntity.setAUTO(autoOrManual+"");
        if(!RobotApplication.TEST){
            if(mtsRobotSocketNative != null) {
                mtsRobotSocketNative.send_data_native((new  Gson()).toJson(switchEntity).toString());
            }
        }


    }

    //控制小车
    class myFingerEven implements OnRockerListener {
        byte[] value = new byte[1];
        @Override
        public void onRocker(int which) {
            Log.d(TAG, "which==" + which);
            int value = -1;
            if (which == 0) {
                value = ClientUtils.stopZ;
            } else {
                zl = 0x01 << (which - 1);
                switch (zl) {
                    case 0x01:
                        value = ClientUtils.stopA;//摇杆1
                        Log.d(TAG, "which stopA==" + value);
                        break;
                    case 0x02:
                        value = ClientUtils.stopB;//摇杆2
                        break;
                    case 0x04:
                        value = ClientUtils.stopC;//摇杆3
                        break;
                    case 0x08:
                        value = ClientUtils.stopD;//摇杆4
                        break;
                    case 0x10:
                        value = ClientUtils.stopE;//摇杆5
                        break;
                    case 0x20:
                        value = ClientUtils.stopF;//摇杆6
                        break;
                    case 0x40:
                        value = ClientUtils.stopG;//摇杆7
                        break;
                    case 0x80:
                        value = ClientUtils.stopH;//摇杆8
                        break;
                }
            }
            if (ClientUtils.connectFlag) {
                final int valueSend = value;
                Log.d(TAG, "which valueSend==" + valueSend);
                new Thread("send") {
                    @Override
                    public void run() {
                        Network.SomeRequest request = new Network.SomeRequest();
                        request.sendType = 0;
                        request.type = valueSend;
                        LogUtil.d(TAG, "客户端发送的 request.sendType==" + request.sendType);
                        ServiceClient.client.sendTCP(request);
                    }
                }.start();
            } else {
                Toast.makeText(ControlActivity.this, "没有连接服务端，请连接", Toast.LENGTH_SHORT).show();
            }
        }
        @Override
        public void onRocker(MySurfaceView mySurfaceView, int which) {
            // TODO Auto-generated method stub

        }
    }
    /*
    让aikit进行人脸识别，但目前来说，用不上
    */
    private void send(String name){
        if(!TextUtils.isEmpty(name)){
            final QuerySQLEntity.RequestQuery requestQuery = new QuerySQLEntity.RequestQuery();
            requestQuery.type = Constants.QUERYCODE;
            requestQuery.name = name;
            new Thread("send") {
                @Override
                public void run() {
                    super.run();
                    ServiceClient.client.sendTCP(requestQuery);
                }
            }.start();

        }

    }
private String getName(Context c){
        SharedPreferences sharedPreferences = c.getSharedPreferences("data",Context.MODE_PRIVATE);
        return sharedPreferences.getString("username",null);

}
    @Override
    public void operateConfirm(Object o) {
        //需要给robot发消息，进行人脸识别确认

        if(o instanceof ContentMessageBean){
            switch (((ContentMessageBean) o).getFRAME()){
                case TSRobotSocketNative.INFORM://"1007" ://ros给client 发任务描述
                    Message msg = handler.obtainMessage();
                    msg.arg1 = 17;
                    msg.obj = o;
                    handler.sendMessage(msg);
                    break;
            }
        }
//        else if(o instanceof MessageBean){
//            switch (((MessageBean) o).getFRAME()){
//                case TSRobotSocketNative.OPERATIONCHECK://"1009"://动作确认了
//                    MessageBean messageBean = new MessageBean();
//                    messageBean.setFRAME("1005");
//                    messageBean.setID(  ((MessageBean) o).getID());
//
//                    alert("动作再次确认？",messageBean.getFRAME(),messageBean);
//                    break;
//
//            }
//        }
    }
    @Override
    public void getInfoFaceData(final String name, final int x, final int y, final int w, final int h) {
        //标示位，接收到ros人脸识别的请求，才可以进行人脸识别
        Log.d(TAG,"@@wp name +" + name + "...."+ getName(ControlActivity.this) + "--"+name.equals(getName(ControlActivity.this)));
        if(mtsRobotSocketNative.isConfirm()){
            Log.d(TAG,"@@wp name +" + name + "...."+ getName(ControlActivity.this) + "--"+name.equals(getName(ControlActivity.this)));
            if(RobotApplication.special){


                try {
                    Thread.sleep(1000);
                }catch (Exception e){

                }

                MessageBean messageBean = new MessageBean();
                messageBean.setFRAME("1004");
                messageBean.setID(name);
                Message msg= handler.obtainMessage();
                msg.arg1 = 16;
                msg.obj = messageBean;
                handler.sendMessage(msg);
            }else{
                inflateFakeData(name, x, y, w, h);
                LogUtil.d(TAG, "开始识别画框 x==" + x + ",,y==" + y + ",,w==" + w + ",,h==" + h);
                if(name.equals(getName(ControlActivity.this))){
//                Toast.makeText(ControlActivity.this,"识别到人脸"+ name,Toast.LENGTH_SHORT).show();
                    //弹出dialog，提示用户检测到人脸了
                    MessageBean messageBean = new MessageBean();
                    messageBean.setFRAME("1004");
                    messageBean.setID(name);
                    Message msg= handler.obtainMessage();
                    msg.arg1 = 16;
                    msg.obj = messageBean;
                    handler.sendMessage(msg);
            }





//                alert("已检测到" + name, messageBean.getFRAME(),messageBean);
            }
        }else{
            LogUtil.d(TAG, "@@wp不开始识别画框");
        }

    }

    @Override
    public void getSensorParam(Object obj) {


        if(obj instanceof QuerySQLEntity.ResponseQuery){
            QuerySQLEntity.ResponseQuery response = (QuerySQLEntity.ResponseQuery) obj;
            if(response.frame.equals("1013")){
                Message msg = handler.obtainMessage();
                msg.arg1 = 15;
                msg.obj = response;
                handler.sendMessage(msg);
            }
        }
    }

    private AlertDialog alertDialog;

    private void alert(final String name){
        if(this.isFinishing()) return;
        if(!isShow) return;
        if (alertDialog != null && alertDialog.isShowing()){return;}

        final EditText edt = new EditText(this);
        alertDialog = new AlertDialog.Builder(ControlActivity.this)
                .setTitle("添加任务描述")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setView(edt)
                .setMessage(edt.getText().toString().trim())
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        if (ClientUtils.connectFlag) {


                            final TaskMessageBean tmb = new TaskMessageBean();
                            tmb.setID(name);
                            tmb.setFROM(startPointName);
                            tmb.setTO(endPointName);
                            tmb.setFRAME("1003");
//                            tmb.setTXT("拿一张港币");
                            if(edt.getText().toString().trim() != null){
                                tmb.setTXT(edt.getText().toString().trim());
                            }else{
                                return;
                            }
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    mtsRobotSocketNative.send_data_native(new Gson().toJson(tmb));
                                }
                            }).start();
                            if(alertDialog.isShowing()) {
                                alertDialog.dismiss();
                            }

                        } else {
//                            Looper.getMainLooper();
//                            Toast.makeText(getApplicationContext(), "没有连接服务端，请连接", Toast.LENGTH_SHORT).show();
//                            Looper.loop();
                            Message msg = handler.obtainMessage();
                            msg.arg1 = 200;
                            msg.obj = "没有连接服务端，请连接";
                            handler.sendMessage(msg);
                        }
                    }
                })
                .show();

    }


    private void alert(String content, final String fram, final Object o){
        if(this.isFinishing()) return;
        if(!isShow) return;
        if (alertDialog != null && alertDialog.isShowing()){return;}

        alertDialog = new AlertDialog.Builder(ControlActivity.this)
                .setTitle("温馨提示")
                .setIcon(android.R.drawable.ic_dialog_info)
//                .setView(edt)
                .setMessage("" +content)
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        if (ClientUtils.connectFlag) {
                            switch (fram){
                                case TSRobotSocketNative.INFORM://"1007"://提示人脸识别开始
                                    mtsRobotSocketNative.setConfirm(true);
                                    break;
                                case TSRobotSocketNative.CONFIRM_ID://"1004"://提示人脸检测识别成功
//                                    if(o instanceof MessageBean){
//                                        new Thread("send") {
//                                            @Override
//                                            public void run() {
//                                                //发送给robot,通知扫描人脸成功
//                                                mtsRobotSocketNative.send_data_native(new Gson().toJson(o));
//                                            }
//                                        }.start();
//                                    }
                                    break;
                                case TSRobotSocketNative.CONFIRM_OP://"1005":
                                    mtsRobotSocketNative.setConfirm(false);
                                    new Thread("send") {
                                        @Override
                                        public void run() {
                                            //发送给robot,通知扫描人脸成功
                                            mtsRobotSocketNative.send_data_native(new Gson().toJson(o));
                                        }
                                    }.start();
                                    break;
                            }
                            if(alertDialog.isShowing()) {
                                alertDialog.dismiss();
                            }

                        } else {
                            Message msg = handler.obtainMessage();
                            msg.arg1 = 200;
                            msg.obj = "没有连接服务端，请连接";
                            handler.sendMessage(msg);

//                            Looper.getMainLooper();
//                                    Toast.makeText(getApplicationContext(), "没有连接服务端，请连接", Toast.LENGTH_SHORT).show();
//                            Looper.loop();
                        }
                    }
                })
                .show();

    }
    @Override
    public void changeModeListener(Object o) {
            if(o instanceof ResponseMessageBean){
                ResponseMessageBean rmb  = (ResponseMessageBean) o;

                Message msg = handler.obtainMessage();
                msg.obj = rmb.getRESPOND();
                msg.arg1 = 14;
                handler.sendMessage(msg);

            }
    }
    @Override
    public void getIsClear() {
        LogUtil.d(TAG, "开始识别清屏");
        inflateFakeData("", -1, -1, -1, -1);
    }

    //人脸画框  不要锁
    private void inflateFakeData(String name, int x, int y, int w, int h) {
        if (x != -1 && y != -1) {
            final ArrayList frames = new ArrayList();
            FaceFrame faceFrame = new FaceFrame(name, x, y, x + w, y + h);
            frames.add(faceFrame);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mDataDrawable.addFrames(frames, vamParams);
                }
            });
            //去掉小车旋转功能
//            if (!isSendSport) {
//                if (ClientUtils.connectFlag) {
//                    new Thread("send") {
//                        public void run() {
//                            isSendSport = true;
//                            Network.SomeRequest request = new Network.SomeRequest();
//                            request.sendType = 0;
//                            request.type = ClientUtils.stopB;
//                            LogUtil.d(TAG, "客户端发送的 request.sendType==旋转");
//                            ServiceClient.client.sendTCP(request);
//                            try {
//                                Thread.sleep(1950);
//                            } catch (InterruptedException e) {
//                                e.printStackTrace();
//                            }
//                            request.sendType = 0;
//                            request.type = ClientUtils.stopZ;
//                            LogUtil.d(TAG, "客户端发送的 request.sendType==停止");
//                            ServiceClient.client.sendTCP(request);
//                            isSendSport = false;
//                        }
//                    }.start();
//                } else {
//                    Toast.makeText(ControlActivity.this, "没有连接服务端，请连接", Toast.LENGTH_SHORT).show();
//                }
//            }
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mDataDrawable.reset();
                }
            });
        }
    }
}
